package Year22_Month04.day17;

public class 螺旋矩阵2 {
    public int[][] generateMatrix(int n) {
        int[][] arr = new int[n][n];

        int left = 0;//定义左边界
        int right = n - 1;//定义右边界

        int top = 0;//定义上边界
        int bottom = n - 1;//定义下边界

        int count = 1;//定义当前加入的数字
        while(count <= n * n){
            //首先从左上往右上遍历
            for (int i = left; i <= right && count <= n*n; i++) {
                arr[top][i] = count;
                count++;
            }
            top++;

            //然后是从右上往右下遍历
            for (int i = top; i <= bottom && count <= n * n; i++) {
                arr[i][right] = count;
                count++;
            }
            right--;

            //然后是从右下往左下遍历
            for (int i = right; i >= left && count <= n * n; i--) {
                arr[bottom][i] = count;
                count++;
            }
            bottom--;

            //然后是从左下往左上遍历
            for (int i = bottom; i >= top && count <= n * n; i--) {
                arr[i][left] = count;
                count++;
            }
            left++;
        }
        return arr;
    }
}
